package com.cyy.view

import com.cyy.controller.SettController
import com.cyy.controller.SettEventModel
import com.cyy.model.GmodelModel
import com.cyy.util.enableConoleLogger
import javafx.geometry.Orientation
import javafx.scene.layout.Priority
import javafx.stage.FileChooser
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.Table
import tornadofx.*

class SetFileView(val gmodel: GmodelModel) : View("My View") {
    val settingList = mutableListOf(
            Sett(1,"Robert", "aa")
    ).asObservable()

    val sett = getSetting(gmodel.settingFile.value)
    val kv = sett.getMap("")
    val a = mutableMapOf<String, String>().asObservable()

    val model: SettModel by inject()

    override val root = vbox(5) {
        shortcut("Ctrl+R") { onRefresh() }
        form() {
            fieldset {
                field("选择配置文件") {
                    button("...") {
                        action {
                            val efset = arrayOf(FileChooser.ExtensionFilter("选择配置文件", "*.*"))

                            val fnset = chooseFile("选择配置文件", efset, FileChooserMode.Single)
                            if (fnset.isNotEmpty()) {
                                gmodel.settingFile.value = "${fnset.first()}"
                                val sett = getSetting(gmodel.settingFile.value)
                                val kv = sett.getMap("")
//                                println(kv.keys)
                                kv.mapEach {
//                                    settingList.add(Sett(this.id,this.key.toString(), this.value.toString()))
                                }
                            }
                        }
                    }
                    textfield(gmodel.settingFile) {
                        text = "E:\\generator\\generator.properties"
                    }
                }
            }
        }

        buttonbar {
            button("Save") {
                enableWhen(model.valid)
                isDefaultButton = true
                action {
                    fire(SettEventModel.AddRequest(model.kkey.value, model.vvalue.value))
//                    resetForm()
                }
            }
            button("Reset") {
                action {
                    resetForm()
                }
            }
        }
        hbox {
            tableview(settingList) {
                title = "配置管理"
                vgrow = Priority.ALWAYS
                prefWidth = 600.0

                val keyCol=column("Key", Sett::kkey).makeEditable()
                column("Value", Sett::vvalue).makeEditable()

                enableCellEditing()
                regainFocusAfterEdit()
                onEditCommit {
                    fire(SettEventModel.UpdateRequest(it))
                    selectionModel.selectNext()
                }
                onSelectionChange {
                    val sett = selectedItem ?: Sett()
                    model.kkey.value = sett.kkey
                    model.vvalue.value = sett.vvalue
                }
                subscribe<SettEventModel.AddEvent>{
                    requestFocus()
                    val nextRow=items.lastIndex+1
                    scrollTo(nextRow)
                    selectionModel.select(nextRow,keyCol)
                    edit(nextRow,keyCol)
                }
                subscribe<SettEventModel.DeleteEvent>{
                    items.remove(selectedItem)
                }
                subscribe<SettEventModel.RefreshEvent> { event ->
                    items.setAll(event.items)
                }
                subscribe<SettEventModel.FilterByNameEvent> {
                    event -> items.setAll(event.items)
                }
                bindSelected(model)
                contextmenu {
                    item("Delete").action {
                        selectedItem?.apply {
                            onDelete()
                        }
                    }
                }
                columnResizePolicy = SmartResize.POLICY
            }
            form {
                fieldset(labelPosition = Orientation.VERTICAL, text = "Edit setting") {
                    field("add or modify key") {
                        textfield(model.kkey).required()
                    }
                    field("add or modify value") {
                        textfield(model.vvalue) {
                            required()
                        }
                    }
                    field {
                        button("Save") {
                            action {
                                //                                println(model.backingValue(model.kkey))
//                                选择的key发生变化才保存,isDirty(key)用来检测key是否发生变化
                                if (model.isDirty(model.kkey).and(kv.containsKey(model.kkey.value).not())) {
                                    settingList.add(Sett(model.id.value.toInt(),model.kkey.value, model.vvalue.value))
                                    kv.set(model.kkey.value, model.vvalue.value)
                                    fire(GenEvent("恭喜，添加修改成功！ "))
                                } else {
                                    fire(GenEvent("添加修改失败！ "))

                                }
                            }
                            enableWhen(model.valid)
                        }
                        button("Delete") {
                            action {
                            }
                            enableWhen(model.valid)
                        }
                    }
                }
            }
        }

    }

    init {
        enableConoleLogger()

        Database.connect("jdbc:sqlite:./app.db", "org.sqlite.JDBC")
        SettController()
//        只需运行一次createTables
//        createTables()
        settingList.remove(0, 1)
        fire(SettEventModel.RefreshRequest())

//        kv.mapEach {
//            settingList.add(Sett(this.hashCode(),this.key.toString(), this.value.toString()))
//        }
    }

    override fun onDelete() {
        model.item?.let {
            fire(SettEventModel.DeleteRequest(model.item.id))
        }
    }
    override fun onRefresh() {
        fire(SettEventModel.RefreshRequest())
    }
    fun resetForm() {
        model.kkey.value = ""
        model.vvalue.value = ""
    }
}

fun ResultRow.toSett() = Sett(
        this[Setts.id],
        this[Setts.kkey],
        this[Setts.vvalue]
)

object Setts : Table() {
    val id = integer("id").autoIncrement().primaryKey()
    val kkey = varchar("kkey", 50)
    val vvalue = varchar("vvalue", 50)
}

class Sett(id: Int = -1, kkey: String = "", vvalue: String = "") {
    val idProperty = intProperty(id)
    var id: Int by idProperty

    val kkeyProperty = stringProperty(kkey)
    var kkey: String by kkeyProperty

    val vvalueProperty = stringProperty(vvalue)
    var vvalue: String by vvalueProperty

    override fun toString() = "$kkey=$vvalue"
}

class SettModel : ItemViewModel<Sett>() {
    val id = bind { item?.idProperty }
    val kkey = bind { item?.kkeyProperty }
    val vvalue = bind { item?.vvalueProperty }
}

